package com.hsnn.medstgmini.common.controller;


import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSON;
import com.hsnn.medstgmini.AesUtil;
import com.hsnn.medstgmini.common.interceptor.StdAttrPathInterceptor;
import com.hsnn.medstgmini.common.model.StdAttachment;
import com.hsnn.medstgmini.util.Pagination;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hsnn.medstgmini.util.ParseDate;
import org.springframework.web.servlet.HandlerInterceptor;

@Controller
@RequestMapping("/attachment")
public class StdAttachmentController  {
	@Value("${file.path}")
	private String filePath;
	@Value("${system.obfuscationRules}")
	private String obfuscationRules;

	public String getPathProp(String data) {
		Properties prop = new  Properties();
		InputStream in = this.getClass().getClassLoader().getResourceAsStream("fileUpload.properties");
		try {
			prop.load(in);
			return prop.getProperty(data);
		} catch (IOException e) {
			return null;
		}
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		boolean bool = true;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		// 禁止缓存
		httpResponse.setHeader("Cache-Control", "no-store");
		httpResponse.setHeader("Pragrma", "no-cache");
		httpResponse.setDateHeader("Expires", 0);
		// 链接来源地址
		String referer = httpRequest.getHeader("referer");
		String serverName = httpRequest.getServerName();

		if (!filePath.contains(serverName)) {
			httpResponse.setHeader("Content-type", "text/html;charset=UTF-8");
			OutputStream os = response.getOutputStream();
			JSONObject returnMap = new JSONObject();// 封装返回信息
			returnMap.put("msg", "非站内请求");
			os.write(JSON.toJSONString(returnMap).getBytes("UTF-8"));
			os.flush();
			os.close();
			bool = false;
		}
		return bool;
	}

	@RequestMapping("getShowImage")
	public void getShowImage(HttpServletRequest request, HttpServletResponse response) {
		try {
				String JPG = "image/jpeg;charset=GB2312";
				String path=request.getParameter("path");
				///////////////////////图片解密大法/////////////////////////
				String filePath = decryptMethod(path);
			    ////////////////////////////////////////////////
				File file = new File(filePath);
				// 获取输出流
				OutputStream outputStream = response.getOutputStream();
				FileInputStream fileInputStream = new FileInputStream(file);
				// 读数据
				byte[] data = new byte[fileInputStream.available()];
				fileInputStream.read(data);
				fileInputStream.close();
				// 回写
				response.setContentType(JPG);
				outputStream.write(data);
				outputStream.flush();
				outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	@RequestMapping("download")
	public void download(String path,HttpServletResponse response) throws Exception {
		String suffix = path.substring(path.lastIndexOf(".")).toLowerCase();
		String filename = UUID.randomUUID().toString() + suffix; 
		response.setHeader("Content-Disposition", "inline; filename="+ URLEncoder.encode(filename, "utf-8"));
        String rootPath = getPathProp("basePath").substring(0,getPathProp("basePath").indexOf("/"));
		File file = new File(rootPath + path);
		FileInputStream fis = new FileInputStream(file);
		byte[] b = new byte[fis.available()];
		fis.read(b);
		response.getOutputStream().write(b);
	}
	
	@RequestMapping("downloads")
	public void downloads(String path,HttpServletResponse response) throws Exception {
		String rootPath = getPathProp("basePath").substring(0,getPathProp("basePath").indexOf("/"));
		File file = new File(rootPath + path);
		FileInputStream fis = new FileInputStream(file);
		byte[] b = new byte[fis.available()];
		fis.read(b);
		response.getOutputStream().write(b);
	}
	
	@RequestMapping("svaeFiles")
	@ResponseBody
	public List<Object> svaeFiles(String suffix,HttpServletRequest request) throws Exception {
		String pathName=request.getParameter("pathName");//图片生成路径
		List<Part> partList = (List<Part>) request.getParts();
		List<Object> resultList = new ArrayList<>();
		for (Part part : partList) {
			if(!part.getName().equals("suffix")){
				InputStream stream = part.getInputStream(); //通过输入流获取图片数据
				String filename = pathName + "." + suffix; // 文件名称
				String rootPath = getPathProp("basePath").substring(0,getPathProp("basePath").indexOf("/"));
				String filePaths = getPathProp("basePath") + filename;
				File destFile = new File(filePaths);
				
				try {
					FileUtils.copyInputStreamToFile(stream, destFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
				Map<String, Object> map = new HashMap<>();
				map.put("name", part.getName());
				map.put("fileName",filename);
				map.put("path", filePaths);
				map.put("url", filePaths.replace(rootPath, ""));
				resultList.add(map);
			}
		}
		return resultList;
	}
	
	
	@RequestMapping("svaeFile")
	@ResponseBody
	public JSONObject svaeFile(HttpServletRequest request) throws Exception {
		JSONObject obj = new JSONObject();
		InputStream stream = request.getPart("file").getInputStream();   //通过输入流获取图片数据 
		String suffix = request.getParameter("suffix");
		String filename = UUID.randomUUID().toString() + "." + suffix; // 文件名称
		//String dirPath = ParseDate.parseShortFormat(new Date()).replaceAll("-", "/"); // 年月路径
		//String filePath= uploadPath + dirPath + "/" + filename;
		
		String filePath = getPathProp("uploadPath") + filename;
		File destFile = new File(filePath);
		try {
			FileUtils.copyInputStreamToFile(stream, destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//obj.put("url", "/attachment/download.html?fileName="+ filename +"&path=" +  filePath);
		obj.put("filePath", filePath);
		return obj;
	}
	
	/**
	 * 
	 * @param suffix   文件后缀
	 * @param path  网路中的文件路径
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("svaePathFile")
	@ResponseBody
	public JSONObject svaePathFile(String suffix,String path) throws Exception {
		JSONObject obj = new JSONObject();
       // String strUrl = "http://www.pptbz.com/pptpic/UploadFiles_6909/201203/2012031220134655.jpg";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		InputStream stream = conn.getInputStream();   //通过输入流获取图片数据    

		String filename = UUID.randomUUID().toString() + "." + suffix; // 文件名称
		String dirPath = ParseDate.parseShortFormat(new Date()).replaceAll("-", "/"); // 年月路径

		String filePath = getPathProp("uploadPath") + dirPath + "/" + filename;
		File destFile = new File(filePath);
		try {
			FileUtils.copyInputStreamToFile(stream, destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		obj.put("url", "/attachment/download.html?fileName="+ filename +"&path=" +  filePath);
		return obj;
	}
	
	
	@RequestMapping("delFile")
	@ResponseBody
	public JSONObject delFile(String path) throws Exception {
		JSONObject obj = new JSONObject();
		//path  = "E:/upload/2016/09/file/267f9e2f07082838dbc3bce8b899a9014d08f104.jpg";
		String rootPath = getPathProp("uploadPath").substring(0,getPathProp("uploadPath").indexOf("/"));
        File f = new File(rootPath + path); // 输入要删除的文件位置
		if(f.exists())
		f.delete();
		return obj;
	}
	/***
	 * 企业类型修改,企业名称修改后  相应的图片附件文件夹名称也需要修改
	 * 需要参数：1.原企业名称 2.现企业名称
	 */
	@RequestMapping("UpdateAllCompNames")
	private void UpdateAllCompNames(HttpServletRequest request) {
		String compNameOld = request.getParameter("compNameOld");
		String compNameNew = request.getParameter("compNameNew");
		/*String filePath = getPathProps()+uploadPath;*/
		String filePath =  getPathProp("basePath");
		File projFile = new File(filePath);

		File[] projFilelist = projFile.listFiles();
		for (File projFileObject : projFilelist) {
			String projPathName = projFileObject.getName();
			String findCompPathName = filePath + "\\" + projPathName;
			File compFile = new File(findCompPathName);
			File[] compFilelist = compFile.listFiles();
			for (File compFileObject : compFilelist) {
				String compPathName = compFileObject.getName();
				if (compPathName.equals(compNameOld)) {
					if (compFileObject.isDirectory()) {
						String newCompPathName = findCompPathName + "\\" + compNameNew;
						compFileObject.renameTo(new File(newCompPathName));
					}
				}
			}
		}
	}

	/***
	 * 解密大法好
	 * @param path
	 * @return
	 * @throws Exception
	 */
	private String decryptMethod(String path) throws Exception {
		/*System.out.print("图片回显路径"+path);*/
		String photoName = path.substring(path.length()-40,path.length());
		String pass = path.substring(0, path.length()-40);
		String decrypt = AesUtil.aesDecrypt(pass, obfuscationRules);
		String lastName = decrypt+photoName;
		String newPath=lastName;
		//文件的根路径
		String rootPath = getPathProp("basePath");
		//文件访问路径
		String filePath=rootPath+newPath;
		return filePath;
	}
}